package com.f6.common.util;

import net.sf.json.JSONObject;

import com.f6.model.SNSUserInfo;

public class AdvancedUtil {
	/**
	 * 通过网页授权获取用户信息
	 * 
	 * @param accessToken 网页授权接口调用凭证
	 * @param openId 用户标识
	 * @return SNSUserInfo
	 */
	public static SNSUserInfo getSNSUserInfo(String accessToken, String openId) {
		SNSUserInfo snsUserInfo = null;
		// 拼接请求地址
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
		System.out.println("请求用户信息地址："+requestUrl);
		// 通过网页授权获取用户信息
		JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
		if (null != jsonObject) {
			try {
				snsUserInfo = new SNSUserInfo();
				// 用户的标识
				try{
					snsUserInfo.setOpenId(jsonObject.getString("openid"));
				}catch(Exception ex){
					//do nothing
				}
				
				// 昵称
				try{
					snsUserInfo.setNickname(jsonObject.getString("nickname"));
				}catch(Exception ex){
					//do nothing
				}
				
				// 性别（1是男性，2是女性，0是未知）
				try{
					snsUserInfo.setSex(jsonObject.getInt("sex"));
				}catch(Exception ex){
					//do nothing
				}
				
				// 用户所在国家
				try{
					snsUserInfo.setCountry(jsonObject.getString("country"));
				}catch(Exception ex){
					//do nothing
				}
				
				// 用户所在省份
				try{
					snsUserInfo.setProvince(jsonObject.getString("province"));
				}catch(Exception ex){
					//do nothing
				}
				
				// 用户所在城市
				try{
					snsUserInfo.setCity(jsonObject.getString("city"));
				}catch(Exception ex){
					//do nothing
				}
				
				// 用户头像
				try{
					snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
				}catch(Exception ex){
					//do nothing
				}
				
				// 用户特权信息
				//snsUserInfo.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class));
			} catch (Exception e) {
				snsUserInfo = null;
				if(jsonObject.containsKey("errcode")){
					String errorCode = jsonObject.getString("errcode");
					String errorMsg = jsonObject.getString("errmsg");
					System.out.println("sns获取用户信息失败 errcode:{"+errorCode+"} errmsg:{"+errorMsg+"}");
				}else if(jsonObject.containsKey("subscribe")){
					String subscribe = jsonObject.getString("subscribe");
					String openid = jsonObject.getString("openid");
					System.out.println("sns获取用户信息失败,用户已取消关注 subscribe:{"+subscribe+"} openid:{"+openid+"}");
				}
			}
		}
		return snsUserInfo;
	}
}
